package util;

import java.io.File;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;

import model.Invoice;
import model.InvoiceDetail;

public class Exporter implements ExportConstants {

	public static boolean exportFile(Invoice invoice, String folderDest) {
		File fileOut = new File(folderDest+"/invoice_" +timeStamp()+".xls");

		try {
			//==========export student=====================//
			PrintWriter writer = new PrintWriter(fileOut, "UTF-8");
			writer.println(HEADER);
			writer.println(RECS_BEGIN);
			writer.flush();
			writer.println(REC_BEGIN);
			writer.println(DATE_BEGIN + invoice.getDate() + DATE_END);
			writer.println(CUSTOMER_NAME_BEGIN + invoice.getCustomerName() + CUSTOMER_NAME_END);
			writer.println(TOTAL_BEGIN + invoice.getTotal() + TOTAL_END);
			writer.println(REC_END);
			Iterator<InvoiceDetail> iter = invoice.getInvoiceDetail().iterator();
			while(iter.hasNext()){
				InvoiceDetail detail = iter.next();
				writer.println(REC_BEGIN);
				writer.println(PRODUCT_NAME_BEGIN + detail.getProductName() + PRODUCT_NAME_END);
				writer.println(QUANTITY_BEGIN + detail.getQuantity() + QUANTITY_END);
				writer.println(PRICE_BEGIN + detail.getPrice() + PRICE_END);
				writer.println(REC_END);
			}
			writer.println(RECS_END);
			writer.flush();
			writer.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	private static String timeStamp(){
		return new Date().toString().replaceAll(":","-");
	}
}
